/**
 * Copyright (C) 2024-2030 Super BilGen & 超亿时代信息技术股份有限公司.All Rights Reserved.
 */
package cn.com.yang.minio.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.com.yang.minio.service.MinioService;

/**
 * @Model cn.com.yang.minio.controller.FileController
 * @Desc  TODO
 * @author yangyijin
 * @since 2025年10月9日-下午7:58:09
 */
@RestController
@RequestMapping("/api/files")
public class FileController {
	private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MinioService minioService;

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件ID（文件名）
     */
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = minioService.uploadFile(file);
            logger.info("File uploaded successfully. File ID: {}",fileName);
            return ResponseEntity.ok().body("File uploaded successfully. File ID: " + fileName);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("Upload failed: " + e.getMessage());
        }
    }

    /**
     * 下载文件
     * @param fileName 文件ID（文件名）
     * @return 文件流
     */
    @GetMapping("/download/{fileName}")
    public ResponseEntity<ByteArrayResource> downloadFile(@PathVariable String fileName) {
        try {
            byte[] data = minioService.downloadFile(fileName);
            ByteArrayResource resource = new ByteArrayResource(data);

            // 设置响应头，指定这是一个附件，让浏览器下载
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
            // 这里可以根据文件类型设置更准确的Content-Type，例如application/octet-stream是通用二进制流
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            logger.info("File download successfully.");
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(data.length)
                    .body(resource);

        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取临时预览链接（推荐这种方式，避免服务器带宽和内存压力）
     * @param fileName 文件ID（文件名）
     * @return 临时URL
     */
    @GetMapping("/preview/{fileName}")
    public ResponseEntity<String> getPreviewUrl(@PathVariable String fileName) {
        try {
            // 生成一个7小时内有效的临时链接
            String url = minioService.getPresignedObjectUrl(fileName, 7);
            return ResponseEntity.ok().body(url);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("Error generating URL: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     * @param fileName 文件ID（文件名）
     */
    @DeleteMapping("/{fileName}")
    public ResponseEntity<String> deleteFile(@PathVariable String fileName) {
        try {
            minioService.deleteFile(fileName);
            logger.info("File deleted successfully.");
            return ResponseEntity.ok().body("File deleted successfully.");
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("Deletion failed: " + e.getMessage());
        }
    }
}